package com.cellulam.framework.core.model;

import com.cellulam.framework.core.utils.BeanUtil;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 不显示总数分页对象
 *
 * @param <E>
 */
@Getter
@Setter
public class LimitResponse<E> {

    public LimitResponse() {
    }

    public LimitResponse(int pageSize, List<E> list) {
        this.pageSize = pageSize;

        if (!CollectionUtils.isEmpty(list)) {
            if (list.size() > pageSize) {
                hasMore = true;
                this.data = list.subList(0, pageSize);
            } else {
                this.data = list;
            }
        }
    }


    public <T> LimitResponse<T> map(Function<? super E, ? extends T> mapper) {
        LimitResponse<T> response = this.map();

        if (!CollectionUtils.isEmpty(this.getData())) {
            response.setData(this.getData().stream()
                    .map(mapper).collect(Collectors.toList()));
        }
        return response;
    }

    public <T> LimitResponse<T> map(Class<T> clazz) {
        LimitResponse<T> response = this.map();

        if (!CollectionUtils.isEmpty(this.getData())) {
            response.setData(BeanUtil.copyByList(this.getData(), clazz));
        }
        return response;
    }

    private <T> LimitResponse<T> map() {
        LimitResponse<T> response = new LimitResponse<>();

        response.setPageSize(this.getPageSize());
        response.setHasMore(this.getHasMore());
        return response;
    }

    public boolean hasData() {
        return !CollectionUtils.isEmpty(this.getData());
    }

    /**
     * 下一页是否有数据
     */
    private Boolean hasMore = false;

    private int pageSize;

    /**
     * 数据
     */
    private List<E> data;

    public static final LimitResponse EMPTY;

    static {
        EMPTY = new LimitResponse<>();
        EMPTY.setData(null);
        EMPTY.setHasMore(false);
    }

    public static final <T> LimitResponse<T> empty() {
        return (LimitResponse<T>) EMPTY;
    }
}
